﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlowDesigner.HelperVision
{
    public class EventAggregator
    {
        private readonly Dictionary<Type, List<WeakReference>> _subscriptions = new Dictionary<Type, List<WeakReference>>();

    // 订阅事件
    public void Subscribe<TEvent>(Action<TEvent> action)
    {
        var eventType = typeof(TEvent);

        if (!_subscriptions.ContainsKey(eventType))
        {
            _subscriptions[eventType] = new List<WeakReference>();
        }

        _subscriptions[eventType].Add(new WeakReference(action));
    }

    // 发布事件
    public void Publish<TEvent>(TEvent eventData)
    {
        var eventType = typeof(TEvent);

        if (_subscriptions.ContainsKey(eventType))
        {
            var subscribers = _subscriptions[eventType];

            foreach (var weakRef in subscribers)
            {
                if (weakRef.IsAlive)
                {
                    var action = weakRef.Target as Action<TEvent>;
                    action?.Invoke(eventData);
                }
            }
        }
    }

    // 清理无效的订阅
    public void CleanUp()
    {
        foreach (var key in _subscriptions.Keys.ToList())
        {
            _subscriptions[key] = _subscriptions[key].Where(wr => wr.IsAlive).ToList();
            if (_subscriptions[key].Count == 0)
            {
                _subscriptions.Remove(key);
            }
        }
    }
    }
    public class EventAggregator1
    {
        // 使用强引用来存储订阅者
        private readonly Dictionary<Type, List<Action<object>>> _subscriptions = new Dictionary<Type, List<Action<object>>>();

        // 订阅事件
        public void Subscribe<TEvent>(Action<TEvent> action)
        {
            var eventType = typeof(TEvent);

            if (!_subscriptions.ContainsKey(eventType))
            {
                _subscriptions[eventType] = new List<Action<object>>();
            }

            // 添加到订阅者列表
            _subscriptions[eventType].Add(eventData => action((TEvent)eventData));
        }

        // 发布事件
        public void Publish<TEvent>(TEvent eventData)
        {
            var eventType = typeof(TEvent);

            if (_subscriptions.ContainsKey(eventType))
            {
                var subscribers = _subscriptions[eventType];

                foreach (var action in subscribers)
                {
                    action(eventData); // 调用事件处理器
                }
            }
        }

        // 清理无效的订阅
        public void CleanUp()
        {
            // 如果没有需要清理的对象，订阅者会一直保留
            // 所以不再需要清理逻辑
        }
    }
}
